package com.hospital.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Spring Security 配置
 *
 * @author Hospital Management System
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF保护
            .csrf().disable()
            // 禁用框架选项
            .headers().frameOptions().disable()
            .and()
            // 配置Session管理为无状态
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置授权规则
            .authorizeRequests()
                // 允许匿名访问的接口 - 使用通配符匹配
                .antMatchers(
                    "/auth/**",                 // 所有认证相关接口
                    "/swagger-ui/**",           // Swagger UI
                    "/swagger-ui.html",         // Swagger UI 主页
                    "/v2/api-docs/**",          // Swagger API 文档
                    "/v3/api-docs/**",          // Swagger 3.0 API 文档
                    "/swagger-resources/**",    // Swagger 资源
                    "/webjars/**",              // Swagger 依赖的 WebJars
                    "/uploads/**",              // 静态资源访问
                    "/druid/**",                // Druid 监控页面
                    "/actuator/**",             // Spring Boot Actuator
                    "/error",                   // 错误页面
                    "/**"                       // 临时允许所有请求（测试用）
                ).permitAll()
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
            .and()
            // 禁用HTTP基本认证
            .httpBasic().disable()
            // 禁用表单登录
            .formLogin().disable()
            // 禁用登出
            .logout().disable();
    }

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
} 